Promise 是用來優化非同步的語法。
let factor = true //非同步事件的成功與否
let condition = function(something) {
return new Promise(function (resolve, reject) {
if(something) {
resolve("成功了");
} else {
reject('失敗QQ');
}
});
}
//-----------------------可簡寫成以下------------------------
/*
let condition = function(something) {
if(something) {
return Promise.resolve("成功了");
} else {
return Promise.reject('失敗QQ');
}
}
*/
//----------------------------------------------------------
condition(factor)
.then(function(val) {
console.log(val);
})
.catch(function(err) {
console.log(err);
});
let factor = true //非同步的事件成功與否
let factor2 = false
let condition = function(something,num) {
if(something) {
return Promise.resolve('第'+ num +"次成功了");
} else {
return Promise.reject('第'+ num +'次失敗QQ');
}
}
condition(factor,1)
.then(function(val) {
console.log('1.'+val);
return condition(factor2,2)
})
.then(function(val) {
console.log('2.'+val);
return condition(factor,3)
})
.then(function(val) {
console.log('3.'+val);
return condition(factor,4)
})
.then(function(val) {
console.log('4.'+val);
})
.catch(error => console.log('錯誤訊息', error))
let factor = true //非同步的事件成功與否
let factor2 = false
let condition = function(something,num) {
return new Promise((resolve,reject)=>{
setTimeout(function(){
if(something) {
resolve('第'+ num +".先成功了");
} else {
reject('第'+ num +'次失敗QQ');
}
},Math.floor(Math.random() * 10)*1000)
})
}
Promise.race([condition(factor2,1),condition(factor,2),condition(factor,3)])
.then((res)=>{
console.log(res)
}
).catch(err => {
console.log(err)
});
//------------------------皆為成功的前提下--------------------------
let factor = true //非同步的事件成功與否
let factor2 = false
let timer = Math.floor(Math.random() * 5)*1000
let condition = function(something,num) {
return new Promise((resolve,reject)=>{
setTimeout(function(){
if(something) {
resolve('第'+ num +".先成功了花了"+timer+'秒');
} else {
reject('第'+ num +'次失敗QQ');
}
},timer)
})
}
Promise.all([condition(factor,1),condition(factor,2),condition(factor,3)])
.then((res)=>{
console.log(res)
}
).catch(err => {
console.log(err)
});
//-------------------------------其中一個失敗狀況下--------------------
let factor = true //非同步的事件成功與否
let factor2 = false
let timer = Math.floor(Math.random() * 5)*1000
let condition = function(something,num) {
return new Promise((resolve,reject)=>{
setTimeout(function(){
if(something) {
resolve('第'+ num +".先成功了花了"+timer+'秒');
} else {
reject('第'+ num +'次失敗QQ');
}
},timer)
})
}
Promise.all([condition(factor,1),condition(factor2,2),condition(factor,3)])
.then((res)=>{
console.log(res)
}
).catch(err => {
console.log(err)
});